package com.qing.qingpicturebackend.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qing.qingpicturebackend.exception.BusinessException;
import com.qing.qingpicturebackend.exception.ErrorCode;
import com.qing.qingpicturebackend.model.dto.user.UserLoginRequest;
import com.qing.qingpicturebackend.model.dto.user.UserQueryRequest;
import com.qing.qingpicturebackend.model.dto.user.UserRegisterRequest;
import com.qing.qingpicturebackend.model.entity.User;
import com.qing.qingpicturebackend.model.enums.UserRoleEnum;
import com.qing.qingpicturebackend.model.vo.UserVO;
import com.qing.qingpicturebackend.service.UserService;

import com.qing.qingpicturebackend.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 86157
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-04-27 23:10:40
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "qing";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    @Override
    public boolean userRegister(UserRegisterRequest request) {
        // 2. 查重
        Long user =this.baseMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getUserAccount, request.getUserAccount()));
        if(user>0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"用户已存在");
        }
        // 3. 加密密码
        String encryptedPassword = getEncryptPassword(request.getUserPassword());
        // 4. 保存用户信息
        User userEntity = new User();
        userEntity.setUserAccount(request.getUserAccount());
        userEntity.setUserPassword(encryptedPassword);
        userEntity.setUserName("无名氏");
        userEntity.setUserRole(UserRoleEnum.USER.getValue());
        boolean save = this.save(userEntity);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败数据库错误");
        }

        return save;
    }

    @Override
    public HashMap<String, Object> userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        // 1. 加密密码
        String encryptedPassword = getEncryptPassword(userLoginRequest.getUserPassword());

        // 2. 查询用户信息
        User user = this.baseMapper.selectOne(new LambdaQueryWrapper<User>()
               .eq(User::getUserAccount, userLoginRequest.getUserAccount())
                .eq(User::getUserPassword, getEncryptPassword(userLoginRequest.getUserPassword())));

        if(user==null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"用户名或密码错误");
        }

        // 3. 登录
        StpUtil.login(user.getId());

        // 4. 设置token
        HashMap<String, Object> data = new HashMap<>();
        data.put("token", StpUtil.getTokenValue());
        data.put("user", user);
        return data;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 1. 判断是否登录
        if (!StpUtil.isLogin()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 2. 清除登录状态
        StpUtil.logout();
        return true;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 判断是否登录
        if (!StpUtil.isLogin()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 获取登录用户信息
        Long userId = StpUtil.getLoginIdAsLong();
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        return user;
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (userList == null  || ObjUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(UserVO::objToVO).collect(Collectors.toList());
    }

}




